
const Koa = require('koa')
const bodyParser = require('koa-bodyparser')
// const controller = require('./controllers')
// const apiModel = require('./lib/mysql.js')
const app = new Koa()
// const cors = require('koa-cors')
const jwtKoa = require('koa-jwt')

const sendHandle = require('./middlewares/sendHandle')

const secret = 'lgx_jwt_secret' //秘钥



// 自定义 401错误，没有token，或者token失效
app.use((ctx, next)=> {
    ctx.set("Content-Type", "application/json;charset=utf-8");
    return next().catch((err) => {
        ctx.status = 401;
        if(err.status === 401){
            ctx.body = {
                code: 401,
                message: 'token 失效'
            }
        }else{
            throw err;
        }
    })
})

app.use(sendHandle())
app.use(jwtKoa({secret}).unless({
    path:  [/\/user\/register/, /\/user\/login/, /\/test\/register/]
}))

// app.use(cors()) 前端代理转发，不需要后端跨域处理

// apiModel.insertData(['wclimb','123456','avator','time'])

app.use(bodyParser())
// app.use(controller())


//  路由
app.use(require('./router/test.js').routes())
app.use(require('./router/user.js').routes())
app.use(require('./router/article_type.js').routes())
app.use(require('./router/article.js').routes())


app.listen(3003, () => {
    console.log("app started at port 3003...");
});
